// pages/chat/index.js
let socket;
let pageIndex = 1
let loading = false
let finish = false
let scrollTopNumber = 0
let mostBottomScrollTop = 0
Page({

    /**
     * 页面的初始数据
     */
    data: {
        msgList: [],
        msgToken: '',
        cm_id: 0,
        msgContent: '',
        sendLoading: false,
        userInfo: {},
        shopInfo: {},
        baseURL: wx.api.host,
        shop_id: null
    },
    /**
     * 纯数据字段
     */
    isInit: false,
    isSend: null,
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        console.log('页面加载');
        let aa = `${new Date().getHours()}:${new Date().getMinutes()}:${new Date().getSeconds()}`
        console.log(aa);
        const {
            shop_id
        } = options
        if (!shop_id) console.error('未传 shop_id');
        try {
            const userInfo = wx.getStorageSync('uinfo')
            this.setData({
                userInfo,
                shop_id
            })
        } catch (error) {
            console.error(error);
        }
        this.getShopinfo()
        this.onCreateSocket()
    },
    /**
     * 获取商铺详情
     */
    getShopinfo() {
        let {
            shop_id,
            baseURL
        } = this.data
        wx.http.get(wx.api.shopinfo, {
            shop_id
        }).then(res => {
            let data = res.data
            data.imagesurl = baseURL + data.imagesurl
            this.setData({
                shopInfo: data
            })
        })
    },
    /**
     * websocket 连接
     */
    onCreateSocket() {
        socket = wx.connectSocket({
            url: 'wss://fengzudaojia.com/wss',
        })
        this.onSocket()
    },
    /**
     * websocket 事件
     */
    onSocket() {
        console.log(socket);
        // 监听打开
        socket.onOpen((res) => {
            console.log('打开', res);
            let aa = `${new Date().getHours()}:${new Date().getMinutes()}:${new Date().getSeconds()}`
            console.log(aa);
            console.log('结束');
            wx.hideLoading()
        })

        socket.onMessage((result) => {
            let {
                msgList,
                sendLoading
            } = this.data
            let res = JSON.parse(result.data)
            if (res.string) {
                this.getChatroomtoken(res.string)
            } else {
                sendLoading = false
                this.isSend && clearTimeout(this.isSend)
                if (res.code == 1 || res.code == 2) {
                    msgList.push(res.data)
                } else if (res.code == -1) {
                    wx.showToast({
                        title: '发送失败',
                        icon: 'none'
                    })
                }
                this.setData({
                    msgList,
                    msgContent: '',
                    sendLoading
                }, () => mostBottomScrollTop - scrollTopNumber < 40 && this.autoScrollBottom(300))
            }
        })
        // 监听错误
        socket.onError(err => {
            console.error('错误', err);
            wx.showToast({
                title: err.errMsg,
                icon: 'none',
                duration: 60 * 60 * 1000,
                mask: true
            })
        })
        // 监听关闭
        socket.onClose(res => {
            console.log('关闭', res);
            if (res.code !== 1000) {
                wx.showLoading({
                    title: '重连接中...',
                })
                this.onCreateSocket()
            }

        })
    },
    /**
     * 发送消息
     */
    onSend() {
        let {
            msgToken,
            msgContent
        } = this.data
        let msgObj = JSON.stringify({
            message: msgContent,
            token: msgToken
        })
        socket.send({
            data: msgObj,
            success: res => {
                this.setData({
                    sendLoading: true
                })
                this.isSend = setTimeout(() => {
                    wx.showToast({
                        title: '发送失败',
                        icon: "none"
                    })
                    this.setData({
                        sendLoading: false
                    })
                }, 10000)
            },
            fail: err => {
                console.error(err);
            }
        })
    },
    /**
     * 获取聊天室专属token
     * @param {String} token ws返回的token
     */
    getChatroomtoken(string) {
        wx.http.get(wx.api.chatroomtoken, {
            shop_id: this.data.shop_id,
            string
        }).then(res => {
            this.isInit = true
            this.setData({
                msgToken: res.data.token,
                cm_id: res.data.cm_id
            }, this.gethistoricaldata)
        })
    },
    /**
     * 获取历史消息
     */
    gethistoricaldata() {
        let {
            cm_id,
            msgList,
        } = this.data
        loading = true
        wx.http.get(wx.api.gethistoricaldata, {
            page: pageIndex,
            limit: 20,
            cm_id
        }).then(res => {
            let list = res.data.data.reverse()
            if (this.isInit) {
                msgList = list
            } else {
                msgList.unshift(...list)
            }
            this.isInit = false
            if (list < 20) finish = true
            loading = false
            this.setData({
                msgList,
            }, this.autoScrollBottom)
        })
    },
    /**
     * 监听用户滑动页面事件
     */
    onPageScroll(e) {
        console.log('监听滚动');
        const {
            scrollTop
        } = e
        scrollTopNumber = scrollTop
        if (!loading && !finish && scrollTop < 10) {
            pageIndex += 1
            this.gethistoricaldata()
        }

    },
    /**
     * 判断是否在底部
     */
    showViewScrollTop(cb) {
        const query = wx.createSelectorQuery()
        query.selectViewport().scrollOffset()
        query.exec((res) => cb(res[0].scrollTop))
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },
    /**
     * 自动滚动到底部
     * @param {*} id 消息列表id
     */
    autoScrollBottom(duration = 0) {
        let {
            msgList
        } = this.data
        wx.pageScrollTo({
            selector: `#scroll-${msgList.length-1}`,
            duration,
            success: () => {
                this.showViewScrollTop(top => mostBottomScrollTop = top)
            },
            fail: err => {
                console.error(err);
            }
        })
    },
    /**
     * 拨打电话
     */
    onPhone() {
        let {
            shopInfo
        } = this.data
        wx.makePhoneCall({
            phoneNumber: shopInfo.shop_phone,
            fail: err => {
                console.error(err);
            }
        })

    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {
        socket && socket.close()
    },
})